<?php

    require_once('jacked_pdnetfunctions.php');
    require_once('jacked_satifunctions.php');
	
	//Sources and API key handling!
	
	function getMyUUID(){
			return jackedSession_read("user.Source.uuid");
	}
	
	function getMySourceID(){
		return jackedSession_read("user.Source.id");
	}
	
	function getMyApplicationInfo(){
	    return jackedSession_read("user.Application");
	}
	
	//start a new API session for the given APIKey and UUID
	////returns the new API session id if it all works, 
	////or an array('error' => 'reason') if there's a problem
	function API_open($apiKey, $uuid = null){
	//yeah i know it has more than one return and thats usually a faggotry but whatever
		
		//validate the API key, set up the Source, blah blah
		$approw = jackedDBGetRow(JACKED_APILOL_DB_APPS, "`apiKey` = '$apiKey'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);
		if($approw){
    		////check if this application type requires a uuid or we're supplying that based on ip
            if($approw['device'] == 1){
                if(!$_REQUEST['uuid']){
                    return array('error' => 'No UUID was provided for this device. UUIDs are required for devices.');
                }else{
                    $uuid = $_REQUEST['uuid'];
                }
            }else{
                $uuid = $_SERVER['REMOTE_ADDR'];
            }
            
			/////////// !!!
			//ONLY SOURCE IS CHECKED HERE, TWO APPS ON THE SAME IP/UUID WOULD BE CONSIDERED THE SAME SOURCE
			///////////////////////////////////////////////////////////////////////////////////////////////////
            $sourcedb = jackedDBGetRow(JACKED_APILOL_DB_SOURCES, "`uuid` = '" . trim($uuid) . "'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);
			jacked_debug_dump($sourcedb);
            if($sourcedb){
                //already have a source
                $source = array("id" => $sourcedb['id'], "uuid" => $sourcedb['uuid']);
            }else{
                //need to create a new source for this guy
                $source = array("id" => '', "uuid" => $uuid, "Application" => $approw['id']);
                $newID = jackedDBInsertValues(JACKED_APILOL_DB_SOURCES, $source);
                if($newID){
                    $source['id'] = $newID;
                    $source['Application'] = null;
                }else{
                    return array('error' => 'Couldn\'t create this as a new Source.');
                }
            }
                        
            //write all this into the session            
    		jackedSession_write("user.Source", $source);
    		jackedSession_write("user.Application", $approw);
			jackedSession_write("auth.get", md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']));
    		if(jackedSession_read("auth.post")){
				//leave it
			}else{
				jackedSession_write("auth.post", "false");
			}
			jackedSession_write("auth.openid", array("false"));
    		
		}else{
		    return array('error' => 'No API Key match.');
		}

		
		return session_id();
	}
	
	//KILL IT ALL WITH FIRE
	////BUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUURN
	function API_close(){
	
		jackedSession_write("user", array());
		jackedSession_write("auth.get", array());
		jackedSession_write("auth.openid", array());
		
	}
	
	//boolean: is an API session currently active for me? Here is my session id. HALP?
	function API_active($sid){
	    $good = false;
	
		//dis is a really needs more security.
		if(jackedSession_idExists($sid) && jackedSession_read("auth.get") != "false"){
			if(jackedSession_read("auth.get") == md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']))
				$good = true;
		}
		
		return $good;
	}
	
	//API session stuff
	function API_store($key, $value){
	    //do some checking to make sure its not anything the API uses 
	    if(strpos($key, "user.") == 0 || strpos($key, "auth.") == 0){
	        return false;
	    }
	    
	    jackedSession_write($key, $value);
	    
	    return true;
	}
	
	function API_recall($key){
	    //do some checking to make sure its not anything the API uses 
	    if(strpos($key, "user.") == 0 || strpos($key, "auth.") == 0){
	        return false;
	    }
	    
	    jackedSession_read($key);
	    
	    return true;
	}
	
	function API_getAuth($type){
	    $done = false;
	    switch($type){
	        case 'get':
	            $done = (jackedSession_read('get') == 'true');
	            break;
	        case 'post':
	            $done = (jackedSession_read("auth.post.sessionID") == md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']));
	            break;
	        case 'openid':
	            $oidauth = jackedSession_read('auth.openid');
	            if($oidauth != 'false')
	                $done = $oidauth;
	            break;
	        default:
	            break;
        } 
        
	    return $done;
	}
        
    /////////////////////////////////////////////////////////////////
    //                     API CALL HANDLER!!!!!!WOOOOOOOOOOOOHAMMOCK
    /////////////////////////////////////////////////////////////////
    function api_call($callMethod = 'GET'){
		
		//First, if we're using keys, let's use keys.
		if(JACKED_APILOL_APIKEY_RESTRICT){
			$api_authorized = false; //assume the worst
			
			//check if there's a token being passed
			if($_REQUEST['api']){
				//if so, validate it
				
				if(API_active($_REQUEST['api'])){
					//this is the only way to continue to the actions dispatch
					$api_authorized = true;
				}else{
					api_error('This API connection is not open to you, it may have expired or been closed.', 'You\'re done here, whether you like it or not.');
				}
			}else{
				//if not, see if they're trying to open a new api session
				if($_REQUEST['action'] == 'API_open'){
					//okay, let's try to log them in, but don't validate for the rest of the actions yet. Just api_done their new sessid
					if(!$_REQUEST['key']){
						api_error('No API Key provided', 'Yeah open the locked door without a key. Shut your facehole, dumbass.');
					}else{
						$openres = API_open($_REQUEST['key'], $_REQUEST['uuid']);
						if(is_array($openres)){
							api_error($openres['error'], 'NO DICE, DICKBONER.');
						}else{
							api_done(array('api_token' => $openres, 'ttl' => JACKED_SESSION_EXPIRY));
						}
					}
				}else{
					//well, fuck you too, man. 
					api_error('API access restricted. Use API_open to open a new API connection with your API Key.', 'You can\'t get none of this sweet, sweet data unless I say so, bitch.');
				}
			}
		}
	
		//halt i am reptar
		if(!$api_authorized){
			return false;
		}
		
		//now let's see about some actions
		
		//first we have the ones accessible by every method:
		switch($_REQUEST['action']){
		
			case 'testcode':

			    //
				
				
				break;
		
			case 'API_open':
				api_error('An API session is already open.', 'How much fucking permission do you need? You already have it, stop asking for more.');
				break;
				
			case 'API_close':
			    API_close();
			    api_done('');
			    
			    break;
			
			case 'API_store':
			    if($_REQUEST['key']){
			        if($_REQUEST['value']){
			            $did = API_store($_REQUEST['key'], $_REQUEST['value']);
			            if($did)
			                api_done('');
			            else
			                api_error('Access denied.', 'DON\'T TOUCH ME THERE!');
			        }else{
			            api_error('No value given.', '/dev/null/');
			        }
			        
		            api_error('No key given.', 'Sure I\'ll store that for you. Just don\'t ask for it back.');
			    }
			    break;
			
			case 'API_recall':
			    if($_REQUEST['key']){
		            $did = API_recall($_REQUEST['key']);
		            if($did)
		                api_done(array($_REQUEST['key'] => $did));
		            else
		                api_error('Access denied.', 'DON\'T TOUCH ME THERE!');
		        }else{
		            api_error('No value given.', 'Storing this in /dev/null/');
		        }
		        
			    break;
				
			case 'getPost':
				$postID = $_REQUEST['postID'];
				$tagFormat = $_REQUEST['tagFormat']? $_REQUEST['tagFormat']: 'array';
				if($postID){
					$apd = ($_REQUEST['fields'] == null)? getPost($postID, $tagFormat) : getPost($postID, $tagFormat, $_REQUEST['fields']);

					//make sure it's all there
					$pass = true;
					foreach($apd as $good){
						if($good == null)
							$pass = false;
					}
					
					if($pass)
						api_done($apd);
					else
						api_error("No post data for that ID.", "Why don't you pick a post that actually exists next time, assbag.");
				}else{
					api_error("No Post ID given.", "What the fuck do you want me to do, guess which post you want?");
				}
				
				break; 
						
			case 'getPosts':
			
				$num = $_REQUEST['howMany'];
				$orderby = ($_REQUEST['orderby'])? $_REQUEST['orderby'] : 'date_down';
				$tagFormat = ($_REQUEST['tagFormat'])? $_REQUEST['tagFormat'] : 'array';
				$page = ($_REQUEST['page']) ? $_REQUEST['page'] : 1;
				$fields = ($_REQUEST['fields']) ? $_REQUEST['fields'] : array("id", "decision", "result", "votes", "date", "tags", "voted");
						
				if($num){
								$posts = getPosts($num, $orderby, $page, $tagFormat, $fields);
					
					if(!empty($posts)){
						api_done($posts);
						}else{
							api_error('No posts matched your query.', 'If you were looking for NOTHING, you sure as fuck found it.');
						}
			
				}else{
					api_error('No howMany value.', 'So how many posts do you want? You left it up to me. So I gave you none.');
				}
				break;
			
			case 'getPostsByTagID':
				if($_REQUEST[tagID]){
					$thesePosts = getPostIDsByTagID($_REQUEST['tagID'], $_REQUEST['orderby'], $_REQUEST['howMany'], $_REQUEST['page']);
					
					$tagFormat = $_REQUEST['tagFormat']? $_REQUEST['tagFormat']: 'array';
					
					$result = array();
					foreach($thesePosts as $postID){
					
						$apd = getPost($postID, $tagFormat);
						
						//make sure it's all there
						$pass = true;
						foreach($apd as $good){
							if(empty($good))
								$pass = false;
						}
						
						if($pass)
							$result[] = $apd;
						else
							api_error("No post data for that ID.", "Somehow there's a post that is tagged but doesn't exist. Great.");
					}
					if(!empty($result)){
    					api_done($result);
					}else{
					    api_error('No posts matched your query.', 'If you were looking for NOTHING, you sure as fuck found it.');
					}
					
				}else{
					api_error("No tag given.", "Oh let me just look up NOTHING, that will certainly work, dickless.");
				}           
						
				break;
		/*nah
			case 'getPostsByTagSlug':
				if($_REQUEST[slug]){
					$thesePosts = getPostIDsByTagSlug($_REQUEST['slug'], $_REQUEST['howMany'], $_REQUEST['page']);
					$result = array();
					foreach($thesePosts as $postID){
					
						$apd = getPost($postID);
						
						//make sure it's all there
						$pass = true;
						foreach($apd as $good){
							if(empty($good))
								$pass = false;
						}
						
						if($pass)
							$result[] = $apd;
						else
							api_error("No post data for that ID.", "Somehow there's a post that is tagged but doesn't exist. Great.");
					}
					
					api_done($result);
				}else{
					api_error("No tag given.", "Oh let me just look up NOTHING, that will certainly work, dickless.");
				}           
						
				break;
		*/
			case 'getPostRank':
				$postID = $_REQUEST['postID'];
				if($postID){
					$rank = getPostRank($postID);
					
					if($rank)
						api_done(array("rank" => $rank));
					else
						api_error("No post data for that ID.", "Why don't you pick a post that actually exists next time, assbag.");
				}else{
					api_error("No Post ID given.", "What the fuck do you want me to do, guess which post you want?");
				}
				
				break; 
			
			case 'getPostPart':
						
				$postID = $_REQUEST['postID'];
				
				$decision = (($_REQUEST['decision'] == 'false') || !((bool) $_REQUEST['decision'])) ? false : true;
				$result = (($_REQUEST['result'] == 'false') || !($_REQUEST['result'])) ? false : true;
				$votes = (($_REQUEST['votes'] == 'false') || !($_REQUEST['votes'])) ? false : true;
				$ip = false;
				$tags = (($_REQUEST['tags'] == 'false') || !($_REQUEST['tags'])) ? false : true;
				
				if($postID){
					if($decision || $result || $votes)
						$apd = getPostMeta($postID, $decision, $result, $ip, $votes);
					if($tags)
						$apd[postTags] = getPostTags($postID);
						
					if($decision || $result || $votes || $tags){
						//make sure it's all there
						$pass = true;
						foreach($apd as $good){
							if(empty($good))
								$pass = false;
						}
						
						if($pass)
							api_done($apd);
						else
							api_error("No post data for that ID.", "Why don't you pick a post that actually exists next time, assbag.");
					}else{
						api_error("No data requested.", "What? You thought I was gonna give you an empty data object? HA! Cockshiner.");
					}
				}else{
					api_error("No Post ID given.", "What the fuck do you want me to do, guess which post you want?");
				}
				
				break; 
			
			case 'getPostText':
				$postID = $_REQUEST['postID'];
				if($postID){
					$apd = getPost($postID, array("decision", "result"));
					
					if($apd[decision] && $apd[result])
						api_done($apd);
					else
						api_error("No post data for that ID.", "Why don't you pick a post that actually exists next time, assbag.");
				}else{
					api_error("No Post ID given.", "What the fuck do you want me to do, guess which post you want?");
				}
				
				break;
			
			case 'votedOnPost':
				$postID = $_REQUEST['postID'];
	
				if($postID){
				    //hahahaha this used to be VIU
				    if(didSourceVoteOnPost(getMySourceID(), $postID))
						api_done("true");
					else
						api_done("false");
				}else{
					api_error("No Post ID given.", "What the fuck do you want me to do, guess which post you want?");
				}
				
				break;
			
			case 'votePost':
				$postID = $_REQUEST['postID'];
				$type = ($_REQUEST['type'] ? $_REQUEST['type'] : 'vote');
				
				if($postID){
					if($type == 'vote' || $type == 'sink'){
						//remember VIU? yeah me neither. 
						$doinIt = VoteOnPost($postID, $type, getMySourceID());
						if(!$doinIt){
							api_error("User has already voted.", "If you try to votespam, I swear to god I will cut you.");
						}else{
							api_done($doinIt);
						}
						
					}else{
						api_error("Invalid vote type.", "'" . $type . "'? Seriously? Does that look like 'vote' or 'sink' to you? Are you completely fucking illiterate?");
					}
				}else{
					api_error("No Post ID given.", "What the fuck do you want me to do, guess which post you want?");
				}
				
				break;
				
				
			case 'submitPD':
				$decision = $_REQUEST['decision'];
				$result = $_REQUEST['result'];
				$app = getMyApplicationInfo();
				if($decision){
					if($result){
						if(submitPost($decision, $result, $app['name'])){                    
							api_done('');
						}else{
							api_error("MySQL error: " . mysql_error(JACKED_DEFAULT_LINK), "What the fuck did you to to my beautiful API you bastard?");
						}
					}else{
						api_error("No result given.", "Oh, so nothing happened? Boy this one sure will get posted right away. Yeah definitely.");
					}
				}else{
					api_error("No decision given.", "Yeah, skip the Decision on Poor DECISIONS. Nice work, dickface.");
				}
				
				break;
			
			//GET THE TAGS!
			case 'getTags':
				$fields = ($_REQUEST['fields']) ? $_REQUEST['fields'] : array("id", "usage", "name", "slug");
				$tags = getTags($_REQUEST['howMany'], $_REQUEST['orderby'], $fields, $_REQUEST['page']);
				if($tags){
					api_done($tags);
				}else{
					api_error("No tags found", "I have no idea how the fuck this is even possible. I blame you though.");
				}
				
				break;
				
			/////////////////////////////////
			////OPENID LOGIN//////////////////////////////
			
			//startAuth for openID
			case 'openIDLogin':
				if($_REQUEST['openid_mode']){
					if($_REQUEST['openid_mode'] == 'cancel'){
						api_error('User cancelled authentication.', 'Fine, don\'t log in. See if I care.');
					}else{
						$done = jackedOIDHandleAuthResponse();
						if($done){
							jackedSession_write("auth.openid.identity", $done['identity']);
							jackedSession_write("auth.openid.name", $done['namePerson/friendly']);
							jackedSession_write("auth.openid.email", $done['contact/email']);
							jackedSession_write("auth.openid.gravatar", "http://www.gravatar.com/avatar/" . md5($done['contact/email']) . "?d=identicon&r=r");
							api_done($done);
						}else
							api_error('Login failed.', 'It didn\'t work. Why? Who the fuck knows. It probably hates you.');
					}
				}else{
					$provider = $_REQUEST['providerURL'];
					if($provider){
						$thing = getLoginWithOID($provider);
						api_done($thing);
					}else{
						api_error('No provider given.', 'What the hell do you want to log into? Nowhere? Here.');
					}
				}
				break;
			
			//commentsshit
			////////////////////
			case 'getCommentByID':
				if($_REQUEST['id']){
					$comments = getCommentByID($_REQUEST['id'], $_REQUEST['fields']);
					if($comments)
						api_done($comments);
					else
						api_error('No comments matched your query.', 'That\'s not even a thing, doucheface.');
				}else{
					api_error('No ID given.',  "What the fuck do you want me to do, guess which comment you want? You know, you're a real dickhead.");
				}
				break;
				
			case 'getCommentsForPost':
				if($_REQUEST['postID']){
					
					if($_REQUEST['page'] && !$_REQUEST['howMany']){
						api_error('No howMany value.', 'So how many comments do you want? You left it up to me. So I gave you none.');
						
					}else{
						$page = ($_REQUEST['page'])? $_REQUEST['page'] : 1;
						$approved = ($_REQUEST['approved'])? true : false;
						
						$comments = getCommentsForPost($_REQUEST['postID'], $_REQUEST['howMany'], $approved, $page, $_REQUEST['fields']);
						if($comments)
							api_done($comments);
						else
							api_error('No comments matched your query.', 'That\'s not even a thing, doucheface.');
					}
				}else{
					api_error('No ID given.',  "What the fuck do you want me to do, guess which post you want?");
				}
				break;
				
			case 'getCommentThreadForPost':
				if($_REQUEST['postID']){
					$comments = getCommentThreadForPost($_REQUEST['postID']);
					if($comments)
						api_done($comments);
					else
						api_error('No comments matched your query.', 'That\'s not even a thing, doucheface.');
				}else{
					api_error('No ID given.',  "What the fuck do you want me to do, guess which post you want?");
				}
				break;
			
			case 'postComment':
				if($_REQUEST['comment']){
					
					if($_REQUEST['postID']){
						$did = postComment($_REQUEST['postID'], $_REQUEST['comment'], $_REQUEST['reply-to']);
						if($did)
							api_done(array("id" => $did));
						else
							api_error('Not logged in. Use openIDLogin to authenticate first.', 'I\'m sure as fuck not letting you post anything until I have your name and email so I can find a way to kick your ass when you ruin everything.');
					}else{
						api_error('No post ID given.', 'This comment will float in the tubes attached to no post whatsoever forever. Nice work, dickless.');
						
					}
				}else{
					api_error('No comment given.',  "No comment.");
				}
				break;
		
			//HAHAHA, OH WOW    
			case 'whosthatpokemon':
				if($_REQUEST['its'] == 'pikachu')
					api_done('GOD DAMMIT AAAAGH');
				else
					api_error('PEBKAC.', 'Way to ruin the joke, fuckfag.');
				break;    
				
			case 'kirby':
				switch($_REQUEST['type']){
					case 'high':
						api_done('<(0_0)>');
						break;
					case 'boxing':
						api_done('(@\'.\')@ @(\'.\'@)');
						break;
					case 'asshole':
						api_done('^(-_-)^');
						break;
					case 'happy':
						api_done('<(^_^)>');
						break;
					case 'covereyes':
						api_done('(>_<)');
						break;
					case 'pointing':
						api_done('<-(-_<--)');
						break;
					case 'kirbycide':
						api_done('<(X_x<)· - - - - ¬(\'-\'<)');
						break;
					case 'FIRETHELAZAR':
						api_done('^(-.-)>(=========');
						break;
					case 'hammertime':
						api_done('(^\'-\')^ (^\'-\')> (>\'-\')> <(\'-\'^) ^(\'-\'^) (^\'-\')^ (^\'-\')> (>\'-\')> <(\'-\'^) ^(\'-\'^)');
						break;
						
					default:
						api_error('No kirby type.', 'WHAT THE FUCK KIND OF KIRBY YOU WANT YOU GOTTA TELL ME NOW GODDAMN SHIT AAAAGH');
						break;
				}    
				break;
				
			case 'breakMyShit':
				echo "hey if you say so.<br /><br /><br /><br />";
				var_dump(Array( 'ha' => 'ha', 'haha' => 'ha', 'hahaha' => 'ha', 'hahahaha' => 'ha' ));
				api_error("LOL", "LOL");
				break; //<------loooooooooolololololol
				
			case 'whatsup':
				api_done('Oh, not much, you? Just hangin out, bein an api, doin api things.');
				break;
				
			case 'boobs':
				api_done('( . Y . )');
				break; 
				  
			default:
				//if that didn't get it, let's see if the POST api has something to say
				if($callMethod == 'POST'){
					include('jacked_apilolfunctions_post.php');
				}else{
					//oh guess not.
					api_error("No API action was requested.", "If you want something, fucking ask for it.");
				}
				break;
		}
			
		
    }
?>
